﻿using System;
using System.Globalization;
using System.Windows.Forms;
using System.Linq;
using Microsoft.TeamFoundation.WorkItemTracking.Controls;
using Microsoft.TeamFoundation.WorkItemTracking.Client;

namespace TfsMerge.View
{
    public sealed partial class WorkItemView : BaseForm
    {
        readonly WorkItem _wi;
        readonly WorkItemFormControl _wiControl;

        public WorkItemView(WorkItem wi)
        {
            InitializeComponent();

            Text = string.Format("{0} {1}: {2}", wi.Type.Name, wi.Id, wi.Title);

            _wiControl = new WorkItemFormControl {Item = wi, ReadOnly = false, Dock = DockStyle.Fill};
            panel.Controls.Add(_wiControl);

            _wi = wi;
            _wi.FieldChanged += WiFieldChanged;
            WiFieldChanged(null, null);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                if (_wiControl != null)
                {
                    _wiControl.Dispose();
                }

                components.Dispose();
            }
            base.Dispose(disposing);
        }

        void WiFieldChanged(object sender, WorkItemEventArgs e)
        {
            if (_wi.Fields.Cast<Field>().Any(field => !field.IsValid))
                toolStripStatusLabel1.Text = _wiControl.GetFirstFieldError();
            else
                toolStripStatusLabel1.Text = string.Empty;
        }

        private void SaveToolStripButtonClick(object sender, EventArgs e)
        {
            if (_wi == null)
                return;

            if (_wi.Fields.Cast<Field>().Any(field => !field.IsValid))
            {
                MessageBox.Show("Some field of work item is not valid...", "Information...");
                return;
            }

            try
            {
                _wi.Save();
            }
            catch (Exception x)
            {
                MessageBox.Show(x.ToString(), "Error...");
            }
        }

        private void CopyToolStripButtonClick(object sender, EventArgs e)
        {
            Clipboard.SetText(_wi.Id.ToString(CultureInfo.InvariantCulture));
        }
    }
}